package com.nondo.rdp.finance.service.impl.analysis;

import com.nondo.rdp.auth.domain.Role;
import com.nondo.rdp.auth.domain.User;
import com.nondo.rdp.auth.endpoint.model.Page;
import com.nondo.rdp.finance.domain.analysis.Analysis;
import com.nondo.rdp.finance.domain.analysis.AnalysisCollection;
import com.nondo.rdp.finance.repository.analysis.AnalysisCollectionRepository;
import com.nondo.rdp.finance.service.analysis.AnalysisCollectionService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

@Transactional
@Service
public class AnalysisCollectionServiceImpl implements AnalysisCollectionService {
    @Autowired
    AnalysisCollectionRepository analysisCollectionRepository;

    @Override
    public AnalysisCollection findOne(Long id) {
        return this.analysisCollectionRepository.findOne(id);
    }

    @Override
    public AnalysisCollection save(AnalysisCollection analysisCollection) {
        return this.analysisCollectionRepository.save(analysisCollection);
    }

    @Override
    public void delete(Long id) {
        this.analysisCollectionRepository.deleteById(id);
    }

    @Override
    public AnalysisCollection findByAnalysisAndUser(Analysis analysis, User user) {
        return this.analysisCollectionRepository.findByAnalysisAndUser(analysis, user);
    }

    @Override
    public Page<AnalysisCollection> findAll(Page<AnalysisCollection> page, AnalysisCollection analysisCollection) {
        Sort sort = new Sort(Sort.Direction.DESC, "createDate");
        PageRequest pageRequest = new PageRequest(page.getPageNumber(), page.getPageSize(), sort);
        org.springframework.data.domain.Page<AnalysisCollection> dictPage = analysisCollectionRepository.findAll((root, query, builder) -> {

            List<Predicate> predicates = new ArrayList<>();
            if (StringUtils.isNotEmpty(analysisCollection.getTitle())) {
                predicates.add(builder.like(root.get("title"), "%" + analysisCollection.getTitle() + "%"));
            }
            if (analysisCollection.getUser() != null) {
                predicates.add(builder.equal(root.get("user"), analysisCollection.getUser().getId()));
            }
            predicates.add(builder.like(root.get("delFlag"), Role.DEL_FLAG_NORMAL));
            Predicate[] predicatesArray = new Predicate[predicates.size()];
            predicates.toArray(predicatesArray);
            return builder.and(predicatesArray);

        }, pageRequest);

        return new Page<AnalysisCollection>(dictPage);
    }
}